Looping Examples
For Loop
const spells = ["Lumos", "Expelliarmus", "Protego", "Morsmordre", "Episkey", "Accio", "Crucio", "Obliviate"];
function forLoopExample() {
for (let i = 0; i < spells.length; i++) {
console.log(spells[i]);
}
}
For Each Loop
const spells = ["Lumos", "Expelliarmus", "Protego", "Morsmordre", "Episkey", "Accio", "Crucio", "Obliviate"];
function forEachLoopExample() {
spells.forEach((item, index) => {
console.log(`Index: ${index}, Element: ${item}`);
});
}
While Loop
const spells = ["Lumos", "Expelliarmus", "Protego", "Morsmordre", "Episkey", "Accio", "Crucio", "Obliviate"];
function whileLoopExample() {
let index = 0;
while (index < spells.length) {
console.log(`Index: ${index}, Element: ${spells[index]}`);
index++;
}
}
Do While Loop
const spells = ["Lumos", "Expelliarmus", "Protego", "Morsmordre", "Episkey", "Accio", "Crucio", "Obliviate"];
function doWhileLoopExample() {
let index = 0;
do {
console.log(`Index: ${index}, Element: ${spells[index]}`);
index++;
} while (index < spells.length);
}
Iteration with Map
const spells = ["Lumos", "Expelliarmus", "Protego", "Morsmordre", "Episkey", "Accio", "Crucio", "Obliviate"];
function mapLoopExample() {
const result = spells.map((item, index) => {
return `Index: ${index}, Element: ${item}`;
});
console.log(result);
}